import { getEntireRoomList } from "@/services/modules/entire"
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"

// 异步请求部分
export const fetchEntireData = createAsyncThunk('fetchData', async (payload, { dispatch, getState }) => {
    // 获取状态
    const state = getState().entire
    const currentPage = state.currentPage
    dispatch(changeIsloading(true))
    await getEntireRoomList(currentPage * 20).then(res => {
        // 获取列表和总页数
        dispatch(changeRoomList(res.list))
        dispatch(changeTotalCount(res.totalCount))
    })
    dispatch(changeIsloading(false))
})

const entireStore = createSlice({
    name: "entire",
    initialState: {
        // 当前页码
        currentPage: 0,
        // 房间列表
        roomList: [],
        // 总房间数
        totalCount: 0,
        // 是否正在加载
        isloading: false,
    },
    reducers: {
        // 修改当前页码
        changeCurrentPage(state, action) {
            state.currentPage = action.payload
        },
        // 修改房间列表
        changeRoomList(state, action) {
            state.roomList = action.payload
        },
        // 修改总页码
        changeTotalCount(state, action) {
            state.totalCount = action.payload
        },
        // 修改是否正在加载
        changeIsloading(state, action) {
            state.isloading = action.payload
        }
    }
})
// 按需导出
export const {
    changeCurrentPage,
    changeRoomList,
    changeTotalCount,
    changeIsloading
} = entireStore.actions
// 导出整个reducer
export default entireStore.reducer